/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lmx.repoDomain.repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lmx.common.constants.CommonConstants;
import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.persistence.service.AccountService;
import com.lmx.persistence.service.CommonService;
import com.lmx.persistence.service.CustomerExtendService;
import com.lmx.persistence.service.CustomerLeaveService;
import com.lmx.persistence.service.CustomerService;
import com.lmx.persistence.service.NursingService;
import com.lmx.persistence.service.WorkPlaceService;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.Bed;
import com.lmx.repoDomain.tmodel.Customer;
import com.lmx.repoDomain.tmodel.CustomerExtend;
import com.lmx.repoDomain.tmodel.Dicttype;

import io.katharsis.queryParams.QueryParams;
import io.katharsis.repository.annotations.JsonApiFindAll;
import io.katharsis.repository.annotations.JsonApiFindOne;
import io.katharsis.repository.annotations.JsonApiResourceRepository;
import io.katharsis.repository.annotations.JsonApiSave;

@JsonApiResourceRepository(Customer.class)
@Component
public class CustomerRepository extends BaseRepository<Customer> {

	@Autowired
	private CommonService commonService;

	@Autowired
	private CustomerService customerService;

	@Autowired
	private WorkPlaceService workPlaceService;

	@Autowired
	private NursingService nursingService;

	@Autowired
	private AccountService accountService;

	@Autowired
	private CustomerLeaveService customerLeaveService;
	@Autowired
	private CustomerExtendService customerExtendService;

	@PostConstruct
	public void init() {
		dslJpaService.setEntityClass(Customer.class);
	}

	/**
	 * TODO 用一句话描述这个方法
	 *
	 * @author ytche
	 * @param customer
	 * @return
	 * @date 2017年7月12日 下午3:28:45
	 */
	@SuppressWarnings("unchecked")
	@Override
	@JsonApiSave
	public Customer save(Customer customer) {
		// TODO 这里的判断逻辑需要重构一下
		Map<String, List<Object>> map = ActionContextHolder.getContext().getPayloadDatas();
		Bed bednew = null;
		// Bed bedOld = null;
		Dicttype bedIdle = commonService.getDicttype(CommonConstants.DICTTYPE.BED_STATUS_1.label());
		if (customer.getId() == null) {
			// 判断身份证
			List<Customer> data = super.checkJujia() ? customerService.checkCardCode(customer.getCardCode())
					: customerService.getCustomerByCardCode(customer.getCardCode());
			if (data != null && data.size() > 0) {
				customer.setErrcode(3);// 身份证重复
				throw new BusinessException(null, CommonConstants.ERROR_CODE.CARDCODE_ERROR.label(), null);
			}
			customer = (Customer) dslJpaService.create(customer);
			customerService.operateCreateCustomer(customer);// 判断是否直接生成，
															// 否（生成账户以及充值记录）
															// 是（ ）
			if (super.checkJujia()) {
				customerService.createUser(customer);
				if (map.containsKey("customerExtend") && map.get("customerExtend") != null) {
					CustomerExtend extend = (CustomerExtend) map.get("customerExtend").get(0);
					extend.setCustomer(customer);
					extend = customerExtendService.save(extend);
					customer.setCustomerExtend(extend);
				}

			}
			if (customer.getCustomerExtend() == null) {
				CustomerExtend extend = new CustomerExtend();
				extend.setTenant(customer.getTenant());
				extend.setCustomer(customer);
				this.customerExtendService.create(extend);
				customer.setCustomerExtend(extend);
			}
			return customer;
		} else {

			if (customer.getDelStatus() == 1) {// 删除
				if (customer.getBed() != null) {
					bednew = customer.getBed();
					workPlaceService.changeDedStauts(bednew, bedIdle);
				}
				dslJpaService.update(customer);
			} else { // 修改
				Customer oldData = customerService.getCustomer(customer);
				if (super.checkJujia()) {
					if (!customer.getCardCode().equals(oldData.getCardCode())) {
						List<Customer> data = this.customerService.checkCardCode(customer.getCardCode());
						if (data != null && data.size() > 0) {
							customer.setErrcode(3);// 身份证重复
							throw new BusinessException(null, CommonConstants.ERROR_CODE.CARDCODE_ERROR.label(), null);
						}
					}
					dslJpaService.update(customer);
					customerService.updateUser(customer);
					if (map.containsKey("customerExtend") && map.get("customerExtend") != null) {
						CustomerExtend extend = (CustomerExtend) map.get("customerExtend").get(0);
						extend.setCustomer(customer);
						extend = customerExtendService.save(extend);
						customer.setCustomerExtend(extend);
					}
				} else {
					int updateFlag = 1;
					// 判断身份证
					if (oldData.getCardCode() != null && oldData.getCardCode().equals(customer.getCardCode())) {

					} else {
						List<Customer> data = customerService.getCustomerByCardCode(customer.getCardCode());
						if (data == null || data.size() == 0) {

						} else {
							updateFlag = 0;
						}
					}
					if (updateFlag == 1) {
						dslJpaService.update(customer);
						customerService.copyFlowDataFromCustomer(customer);
					} else {
						customer.setErrcode(3);// 身份证重复
						throw new BusinessException(null, CommonConstants.ERROR_CODE.CARDCODE_ERROR.label(), null);
					}
				}
			}

		}
		return customer;
	}

	@Override
	@JsonApiFindAll
	public Iterable<Customer> findAll(final QueryParams requestParams) {
		Map<String, String> keyMap = CommonUtil.getKeyMapByFilter(requestParams);
		String queryType = keyMap.get("queryType");
		String flagQueryType = keyMap.get("flagQueryType");
		Iterable<Customer> dataList = new ArrayList<>();
		if (flagQueryType != null && "customerWithFlag".equals(flagQueryType)) {
			// 判断老人是否有单周（planDetail为空）以及全年护理计划（planitem模版为空），护理方案（是否有project）
			dataList = super.findAll(requestParams);
			return customerService.getCustomerWithFlag(dataList);
		}
		if (queryType != null && "customerWithoutProject".equals(queryType)) {
			return customerService.getCustomerListFilterProject();
		} else if (queryType != null && "customerWithDrugs".equals(queryType)) {
			return customerService.getCustomerListFilterDrugs();
		} else if (queryType != null && queryType.matches("^(eid)(\\d+)$")) {
			String eid = queryType.replace("eid", "");
			return customerService.getCustomerByEID(Long.parseLong(eid));
		} else if (queryType != null && queryType.matches("^(startLive)(\\d+)$")) {
			String cid = queryType.replace("startLive", "");
			return customerService.startLiveVideo(Long.parseLong(cid));
		} else if (queryType != null && queryType.matches("^(endLive)(\\d+)$")) {
			String cid = queryType.replace("endLive", "");
			return customerService.stopLiveVideo(Long.parseLong(cid));
		} else {
			dataList = super.findAll(requestParams);
		}
		for (Customer customer : dataList) {
			customer.setLeaveStatus(this.customerLeaveService.getLeaveStatus(customer));
		}
		return dataList;
	}

	@Override
	@JsonApiFindOne
	public Customer findOne(final Long id, final QueryParams requestParams) {
		Customer customer = null;
		customer = (Customer) dslJpaService.findById(id);
		return customer;
	}
}
